<template>
  <div class="announcements-container">
    <el-card class="announcement-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span class="card-title">公告管理</span>
          <div class="header-right">
            <el-input v-model="searchKeyword" placeholder="搜索公告标题" class="search-input" clearable :prefix-icon="Search" @clear="handleSearch" @keyup.enter="handleSearch" />
            <el-button type="primary" @click="handleAdd" :icon="Plus" class="add-btn">新增公告</el-button>
          </div>
        </div>
      </template>

      <!-- 公告列表 -->
      <el-table v-loading="loading" :data="filteredAnnouncements" border style="width: 100%" row-key="id" highlight-current-row class="announcement-table">
        <el-table-column prop="title" label="标题" min-width="300" align="center">
          <template #default="{ row }">
            <span class="announcement-title-text">《{{ row.title }}》</span>
          </template>
        </el-table-column>
        <el-table-column prop="publisherName" label="发布人" width="120" align="center" />
        <el-table-column prop="publishTime" label="发布时间" width="180" align="center">
          <template #default="{ row }">
            {{ formatDate(row.publishTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="更新时间" width="180" align="center">
          <template #default="{ row }">
            {{ formatDate(row.updateTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click.stop="handleView(row)" :icon="View" circle title="查看" />
            <el-button type="warning" size="small" @click.stop="handleEdit(row)" :icon="Edit" circle title="编辑" />
            <el-button type="danger" size="small" @click.stop="handleDelete(row)" :icon="Delete" circle title="删除" />
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 50, 100]" background layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" prev-text="上一页" next-text="下一页" :pager-count="5" />
      </div>
    </el-card>

    <!-- 公告详情对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="70%" destroy-on-close :close-on-click-modal="dialogType === 'view'" center top="5vh" class="announcement-dialog">
      <div v-if="dialogType === 'view'" class="announcement-detail">
        <h2 class="detail-title">《{{ currentAnnouncement.title }}》</h2>
        <div class="announcement-info">
          <div class="info-item">
            <el-icon>
              <User />
            </el-icon>
            <span>{{ currentAnnouncement.publisherName }}</span>
          </div>
          <div class="info-item">
            <el-icon>
              <Calendar />
            </el-icon>
            <span>{{ formatDate(currentAnnouncement.publishTime) }}</span>
          </div>
          <div class="info-item" v-if="currentAnnouncement.updateTime && currentAnnouncement.updateTime !== currentAnnouncement.publishTime">
            <el-icon>
              <Timer />
            </el-icon>
            <span>{{ formatDate(currentAnnouncement.updateTime) }}</span>
          </div>
        </div>
        <el-divider />
        <!-- 安全地渲染富文本内容 -->
        <div class="content rich-content" v-html="formatContentWithLineBreaks(currentAnnouncement.content)"></div>
      </div>
      <el-form v-else ref="announcementForm" :model="currentAnnouncement" :rules="formRules" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="currentAnnouncement.title" placeholder="请输入公告标题" maxlength="100" show-word-limit />
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <RichTextEditor v-model="currentAnnouncement.content" placeholder="请输入公告内容..." />
          <div class="editor-helper-text">支持常用的富文本格式，如加粗、斜体、列表、表格等</div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span v-if="dialogType !== 'view'" class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitLoading">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete, View, Search, User, Calendar, Timer } from '@element-plus/icons-vue'
import { getAnnouncements, addAnnouncement, updateAnnouncement, deleteAnnouncement } from '@/api/announcement'
import { getUserInfo } from '@/utils/auth'
import RichTextEditor from '@/components/RichTextEditor.vue'
import { sanitizeHtml } from '@/utils/html-sanitizer'

// 数据定义
const announcements = ref([])
const loading = ref(false)
const dialogVisible = ref(false)
const dialogType = ref('view') // view, add, edit
const searchKeyword = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const submitLoading = ref(false)
const announcementForm = ref(null)

// 表单校验规则
const formRules = {
  title: [
    { required: true, message: '请输入公告标题', trigger: 'blur' },
    { min: 2, max: 100, message: '标题长度在2-100个字符之间', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入公告内容', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (!value || value.trim() === '') {
          callback(new Error('请输入公告内容'))
        } else if (value.replace(/<[^>]+>/g, '').trim().length < 5) {
          callback(new Error('内容不能少于5个字符'))
        } else if (value.length > 50000) {
          callback(new Error('内容不能超过50000个字符'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 当前操作的公告
const currentAnnouncement = ref({
  id: null,
  title: '',
  content: '',
  publisherId: null,
  publisherName: ''
})

// 计算属性
const dialogTitle = computed(() => {
  const typeMap = {
    view: '公告详情',
    add: '新增公告',
    edit: '编辑公告'
  }
  return typeMap[dialogType.value] || '公告信息'
})

const filteredAnnouncements = computed(() => {
  if (!searchKeyword.value) {
    return announcements.value
  }
  return announcements.value.filter(item =>
    item.title.toLowerCase().includes(searchKeyword.value.toLowerCase())
  )
})

// 格式化方法
const formatDate = (dateString) => {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

const formatContent = (content) => {
  if (!content) return ''
  // 截取前50个字符，超出部分显示...
  return content.length > 50 ? content.substring(0, 50) + '...' : content
}

const formatContentWithLineBreaks = (content) => {
  if (!content) return ''

  // 首先确保内容安全
  let safeContent = sanitizeHtml(content)

  // 检查内容是否已经包含HTML标签
  const containsHtml = /<[a-z][\s\S]*>/i.test(safeContent)

  // 如果不包含HTML标签，则将换行符转换为<br>，将段落用<p>包装
  if (!containsHtml) {
    // 先将连续的换行符替换为段落分隔符
    safeContent = safeContent
      .replace(/\n{2,}/g, '</p><p>')
      // 将单个换行符替换为<br>
      .replace(/\n/g, '<br>')

    // 确保内容在<p>标签内
    if (!safeContent.startsWith('<p>')) {
      safeContent = '<p>' + safeContent
    }
    if (!safeContent.endsWith('</p>')) {
      safeContent = safeContent + '</p>'
    }
  }

  return safeContent
}

// 方法定义
const fetchAnnouncements = async () => {
  loading.value = true
  try {
    const res = await getAnnouncements()
    announcements.value = res.data
    total.value = res.data.length
  } catch (error) {
    ElMessage.error('获取公告列表失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

const handleAdd = () => {
  // 获取当前登录用户信息
  const userInfo = getUserInfo()

  dialogType.value = 'add'
  currentAnnouncement.value = {
    id: null,
    title: '',
    content: '',
    publisherId: userInfo.id,
    publisherName: userInfo.name
  }
  dialogVisible.value = true
}

const handleView = (row) => {
  dialogType.value = 'view'
  currentAnnouncement.value = { ...row }
  dialogVisible.value = true
}

const handleEdit = (row) => {
  dialogType.value = 'edit'
  currentAnnouncement.value = { ...row }
  dialogVisible.value = true
}

const handleDelete = (row) => {
  ElMessageBox.confirm(
    '是否确定要删除该公告？',
    '删除警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      center: false,
      roundButton: true,
      customClass: 'delete-confirm-dialog',
      distinguishCancelAndClose: true,
      appendToBody: true,
      customStyle: {
        marginTop: '-200px'
      }
    }
  ).then(async () => {
    try {
      await deleteAnnouncement(row.id)
      ElMessage.success('删除成功')
      fetchAnnouncements()
    } catch (error) {
      ElMessage.error('删除公告失败，请稍后重试')
    }
  }).catch(() => {
    // 取消删除，不执行操作
  })
}

const submitForm = () => {
  announcementForm.value.validate(async valid => {
    if (!valid) return

    // 再次检查富文本内容是否为空
    const plainTextContent = currentAnnouncement.value.content.replace(/<[^>]+>/g, '').trim();
    if (!plainTextContent) {
      ElMessage.warning('公告内容不能为空');
      return;
    }

    submitLoading.value = true
    try {
      // 确保内容安全
      currentAnnouncement.value.content = sanitizeHtml(currentAnnouncement.value.content)

      if (dialogType.value === 'add') {
        // 新增公告
        await addAnnouncement(currentAnnouncement.value)
        ElMessage.success('公告发布成功')
      } else if (dialogType.value === 'edit') {
        // 编辑公告
        await updateAnnouncement(currentAnnouncement.value.id, currentAnnouncement.value)
        ElMessage.success('公告更新成功')
      }

      dialogVisible.value = false
      fetchAnnouncements()
    } catch (error) {
      ElMessage.error(error.message || '操作失败，请稍后重试')
    } finally {
      submitLoading.value = false
    }
  })
}

const handleSearch = () => {
  // 通过计算属性自动过滤，不需要额外处理
}

const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
}

const handleCurrentChange = (val) => {
  currentPage.value = val
}

// 初始化
onMounted(() => {
  fetchAnnouncements().then(() => {
    // 检查URL参数中是否有要查看的公告ID
    const urlParams = new URLSearchParams(window.location.search)
    const viewAnnouncementId = urlParams.get('view')

    if (viewAnnouncementId) {
      // 查找对应的公告
      const announcement = announcements.value.find(item => item.id == viewAnnouncementId)
      if (announcement) {
        // 打开查看弹窗
        handleView(announcement)
      }
    }
  })
})
</script>

<style scoped>
.announcements-container {
  padding: 20px;
}

.announcement-card {
  margin-bottom: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 20px;
  font-weight: bold;
  color: #409EFF;
}

.header-right {
  display: flex;
  gap: 15px;
  align-items: center;
}

.search-input {
  width: 300px;
}

.add-btn {
  padding: 10px 20px;
}

.announcement-table {
  margin: 15px 0;
  border-radius: 4px;
}

.announcement-title-text {
  font-weight: 500;
  color: #303133;
  display: block;
  text-align: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  padding: 10px 0;
}

:deep(.el-pagination) {
  padding: 5px 10px;
  border-radius: 4px;
  background-color: #f5f7fa;
}

:deep(.el-pagination .el-pagination__total) {
  font-weight: 500;
}

:deep(.el-pagination .el-pagination__jump) {
  margin-left: 15px;
}

.announcement-detail {
  padding: 0;
  margin-bottom: 10px;
}

.detail-title {
  text-align: center;
  margin: 5px 0 15px;
  font-size: 22px;
  font-weight: bold;
  color: #303133;
}

.announcement-info {
  display: flex;
  justify-content: center;
  gap: 30px;
  margin-bottom: 10px;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 5px;
  color: #606266;
  font-size: 14px;
}

.content {
  line-height: 1.8;
  font-size: 16px;
  text-align: justify;
  padding: 15px 20px;
  background-color: #f9f9f9;
  border-radius: 4px;
  min-height: 180px;
  white-space: pre-wrap;
  word-break: break-word;
}

.content :deep(img) {
  max-width: 100%;
  height: auto;
}

.content :deep(table) {
  border-collapse: collapse;
  width: 100%;
  margin: 10px 0;
}

.content :deep(td),
.content :deep(th) {
  border: 1px solid #ddd;
  padding: 8px;
}

.content :deep(blockquote) {
  margin: 10px 0;
  padding: 10px 20px;
  background-color: #f0f0f0;
  border-left: 4px solid #ccc;
}

.content :deep(pre) {
  background-color: #f0f0f0;
  padding: 10px;
  border-radius: 4px;
  overflow-x: auto;
}

.content :deep(a) {
  color: #409EFF;
  text-decoration: none;
}

.content :deep(a:hover) {
  text-decoration: underline;
}

:deep(.el-dialog__header) {
  margin-right: 0;
  padding: 15px;
}

:deep(.el-dialog__body) {
  padding: 15px 20px;
  max-height: 70vh;
  overflow-y: auto;
}

:deep(.el-dialog__footer) {
  border-top: 1px solid #ebeef5;
  padding-top: 15px;
}

:deep(.el-table thead th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: bold;
  text-align: center;
}

:deep(.el-divider) {
  margin: 10px 0;
}

:deep(.delete-confirm-dialog) {
  border-radius: 8px;
  overflow: hidden;
  position: fixed;
  top: 30% !important;
  transform: translateY(-50%);
}

:deep(.delete-confirm-dialog .el-message-box__header) {
  background-color: #f56c6c;
  padding: 15px;
}

:deep(.delete-confirm-dialog .el-message-box__title) {
  color: #fff;
  font-weight: bold;
  font-size: 18px;
}

:deep(.delete-confirm-dialog .el-message-box__headerbtn .el-message-box__close) {
  color: #fff;
}

:deep(.delete-confirm-dialog .el-message-box__content) {
  padding: 20px;
  font-size: 16px;
  text-align: left;
}

:deep(.delete-confirm-dialog .el-message-box__message) {
  text-align: left;
  padding-left: 10px;
}

:deep(.delete-confirm-dialog .el-message-box__btns) {
  padding: 10px 20px 15px;
}

:deep(.delete-confirm-dialog .el-button--primary) {
  background-color: #f56c6c;
  border-color: #f56c6c;
}

:deep(.delete-confirm-dialog .el-button--primary:hover) {
  background-color: #f78989;
  border-color: #f78989;
}

:deep(.el-table .cell) {
  text-align: center;
}

:deep(.el-form-item__content) {
  width: 100%;
}

:deep(.rich-text-editor-container) {
  width: 100%;
  min-height: 350px;
}

:deep(.w-e-text-container) {
  min-height: 300px;
}

.editor-helper-text {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
  padding-left: 5px;
}

:deep(.announcement-dialog .el-dialog__body) {
  padding: 20px 25px;
  max-height: 70vh;
  overflow-y: auto;
}

:deep(.announcement-dialog .el-dialog__body::-webkit-scrollbar) {
  width: 8px;
  height: 8px;
}

:deep(.announcement-dialog .el-dialog__body::-webkit-scrollbar-thumb) {
  background-color: #c0c4cc;
  border-radius: 4px;
}

:deep(.announcement-dialog .el-dialog__body::-webkit-scrollbar-track) {
  background-color: #f5f7fa;
}

:deep(.announcement-dialog .el-dialog__header) {
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
  background-color: #f5f7fa;
}

:deep(.announcement-dialog .el-dialog__title) {
  font-weight: bold;
  color: #409EFF;
}

:deep(.announcement-dialog .el-dialog__footer) {
  border-top: 1px solid #ebeef5;
  padding: 15px 20px;
}

:deep(.announcement-dialog .el-form-item__label) {
  font-weight: 500;
}

.rich-content {
  line-height: 1.8;
}

.rich-content :deep(p) {
  margin: 12px 0;
}

.rich-content :deep(h1),
.rich-content :deep(h2),
.rich-content :deep(h3),
.rich-content :deep(h4),
.rich-content :deep(h5),
.rich-content :deep(h6) {
  margin: 16px 0 12px;
  line-height: 1.4;
  font-weight: bold;
}

.rich-content :deep(ul),
.rich-content :deep(ol) {
  padding-left: 20px;
  margin: 10px 0;
}

.rich-content :deep(li) {
  margin: 5px 0;
}

.rich-content :deep(br) {
  display: block;
  content: "";
  margin-top: 10px;
}
</style>